
const userDao = require('../service/user_dao')
const passport = require('../util/passport')
const md5 = require('../util/md5solt')
const jwt = require('jsonwebtoken');

module.exports = {
    userlist:async(ctx,next)=>{
        await ctx.render('user/userlist', {})
    },
    
    postlogin:async(ctx)=>{
        const data = ctx.request.body
        // 查询用户
        const user = await userDao.getUserInfo(data.user_id)  
        // 判断用户是否存在
        // console.log('user:'+user.user_name)
        if (!user) {
            //表示不存在该用户
            // ctx.status = 404;
            ctx.status = 200;
            ctx.body = {
                code:-1,
                data:{
                    message: '该用户不存在'
                }
            };
            return;
        }
        //验证密码
        let md5pass = await md5.MD5(data.password,user.solt)
        if(md5pass === user.password){
            const payload = {
                user_id: user.user_id,
                user_name:user.user_name
            };
            //生成token
            const token = jwt.sign(payload, "gamercode", {
                expiresIn: 3600
            });
            console.log("生成token："+ token)
            ctx.status = 200;
            ctx.body = {
                code:1,
                data:{
                    message: '验证成功',
                    token: 'Bearer ' + token
                }
            }
        }else{
            ctx.status = 200;
            ctx.body = {
                code:0,
                data:{
                    message: '密码错误'
                }
            };
        }
    },

    userinfo:async(ctx)=>{
        console.log(ctx.state.user)
        ctx.body = {
            data:{
                message: '用户信息',
                user:ctx.state.user
            }
        };
    }
}



